package org.springcloud.wisdom.springcloud_03_freshman.zfb;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springcloud.wisdom.springcloud_03_freshman.student.entity.Paid;
import org.springcloud.wisdom.springcloud_03_freshman.student.service.PaidService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/alipay")
public class AlipayController {
    //支付宝沙箱网关地址
    private static  final String GATEWAY_URL="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static  final String FORMAT="JSON";
    private static  final String CHARSET="UTF-8";
    //签名方式
    private static  final String SIGN_TYPE="RSA2";
    @Resource
    private  ApliPayConfig apliPayConfig;
    @Resource
    PaidService paidService;

    @RequestMapping("/pay")
    public void pay(String sno, HttpServletResponse httpServletResponse) throws Exception{
        //查询订单信息
        Paid paid=paidService.getPaid(sno);
        if(paid ==null){
            return ;
        }
        //1.创建Client通用sdk提供的Client负责调用支付宝API
        AlipayClient alipayClient=new DefaultAlipayClient(GATEWAY_URL,apliPayConfig.getAppId(),
                apliPayConfig.getAppPrivateKey(),FORMAT,CHARSET,apliPayConfig.getAlipayPublicKey(),
                SIGN_TYPE);
        //2.创建Request并设置Request参数
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setNotifyUrl(apliPayConfig.getNotifyUrl());
        JSONObject bizContent=new JSONObject();
        //商户订单编号唯一的
        bizContent.set("out_trade_no",paid.getSno());
        //总额数
        bizContent.set("total_amount",paid.getMoney());
        //商品名称
        bizContent.set("subject",paid.getPayconn());

        //固定配置
        bizContent.set("product_code","FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
     /*  //支付完程后 自动跳转到本地页面的路径
        request.setReturnUrl("http://localhost:8080/?#/home/freshman/stream");*/
        System.out.println("bizContent:"+bizContent.toString());
        //执行请求拿到响应的结果 返回给浏览器（官方提供的）
        String form="";
        try {
            //调用SDK生成表单
            form=alipayClient.pageExecute(request).getBody();
        }catch (AlipayApiException e){
            e.printStackTrace();
        }
        //返回一个新的表单页面
        httpServletResponse.setContentType("text/html;charset="+CHARSET);
        httpServletResponse.getWriter().write(form);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    @PostMapping("/notify")
    public  void payNotify(HttpServletRequest request) throws Exception{
        System.out.println("notify中的request:"+request);
        System.out.println("notify中的request.getParameter(\"trade_status\"):"+request.getParameter("trade_status"));
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("===================支付宝异步回调========================");
            Map<String,String> params=new HashMap<>();
            Map<String,String[]> requestParams=request.getParameterMap();
            for (String name:requestParams.keySet()){
                params.put(name,request.getParameter(name));
            }
            String sign=params.get("sign");
            String content= AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature=AlipaySignature.rsa256CheckContent(
                    content,sign,apliPayConfig.getAlipayPublicKey(),"UTF-8");
            System.out.println("checkSignature:"+checkSignature);
            //支付宝验签
            if (checkSignature){
                //验证通过
                System.out.println("交易名称："+params.get("subject"));
                System.out.println("交易状态："+params.get("trade_status"));
                System.out.println("交易金额："+params.get("total_amount"));
                System.out.println("商户订单号："+params.get("out_trade_no"));
                System.out.println("支付宝交易凭证号："+params.get("trade_no"));
                System.out.println("买家支付宝唯一id："+params.get("buyer_id"));
                System.out.println("买家付款时间："+params.get("gmt_payment"));
                System.out.println("买家付款金额："+params.get("buyer_pay_amount"));

                String tradeNo=params.get("out_trade_no");
                String paydt=params.get("gmt_payment");
                String alipayTradeNo=params.get("trade_no");//支付宝本身就有的
                System.out.println(tradeNo);
                System.out.println("支付宝订单编号："+alipayTradeNo);
                //更新订单状态为已支付 设置支付信息
                Paid paid=paidService.getPaid(tradeNo);
                paid.setStatus("已缴费");
                paid.setPaydt(paydt);
                paid.setPayno(alipayTradeNo);
                paidService.update(paid);
            }
        }
    }
}
